package com.liuwei.msmall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

/**
 * @Classname MyRabbitMqConfig
 * @Description TODO
 * @Date 2020/7/1 21:00
 * @Created by 刘
 */
@Configuration
public class MyRabbitMqConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;



    //配置rabbitTemplate，
    @PostConstruct//表示这个方法在MyRabbitMqConfig对象创建成功之后执行
    public void initRabbitTemplate(){



        //设置消息发送到breaker中成功后的回调，不管是成功还是失败，都要回调。
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 消息发送到breaker的回调
             * @param correlationData 消息id
             * @param ack 发送是否成功
             * @param cause 消息发送到breaker失败的原因
             */
            @Override
            public void confirm(@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) {
                //TODO 失败之后将消息记录在数据库中，定期扫描发送失败的消息
                if (correlationData!=null){
                    System.out.println("correlationData:"+correlationData.getId()+"==>ack:"+ack+"==>cause:"+cause);
                }

            }
        });

        //设置消息从交换机Exchange投递到队列Queue失败的回调,只有失败的时候才回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {

            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                //TODO 失败之后将消息记录在数据库中，定期扫描发送失败的消息

                System.out.println("message:"+message+"==>replyCode:"+replyCode+
                        "==>replyText:"+replyText+"==>exchange:"+exchange+"==>routingKey:"+routingKey);
            }
        });


    }


}
